<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use App\Models\User;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use App\Models\Profile;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cookie;

class AuthController extends Controller
{
    public function login_view(){
        return view('admin/AuthViews/login');
    }

    public function login(Request $request){
        $email=$request->email;
        $password=$request->password;
        $online=$request->online;

        $rules = ['captcha' => 'required|captcha'];
        $validator = Validator::make(Input::all(), $rules);
        if ($validator->fails())
        {
            return redirect('login')->with('err1','验证码错误,请重新填写')->withInput($request->only(['email','password']));
        }
        else {
                $result = User::where('email',$email)->with('profile')->get();

                foreach ($result as $r){
                    if ($email==$r->email&&Hash::check($password, $r->password)) {
                        if (isset($online)&&$online==1){
                            $request->session()->put('online',1);
                        };
//                        User::where('email',$r->email)->update(['land_at'=>Carbon::now()]);
                        $request->session()->put('user', $r);
                        return redirect('admin/index');
                    }
                }
            return back()->with('err','账户或密码错误');
        }

    }

    public function emailCheck(Request $request)
    {
        $email = $request->input('email');
        $users = User::all()->lists('email');
        foreach ($users as $s) {
            if ($email == $s) {
                return response()->json(array(
                    'msg' => '该账号已注册',
                ));
            }
        }
        return response()->json(array(
            'msg' => '',
        ));
    }

    public function out(Request $request){
        $request->session()->flush();
        Cookie::queue('test','', -1);
        return redirect('index')->with('green_msg','操作成功!');
    }


}
